package com.wanwanbookstore.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
    private static String URL;
    private static String USERNAME;
    private static String PASSWORD;
    private static String DRIVER;

    static {
        // 加载配置文件
        Properties properties = new Properties();
        try (InputStream input = DBUtil.class.getClassLoader().getResourceAsStream("db.properties")) {
            if (input != null) {
                properties.load(input);
                URL = properties.getProperty("jdbc.url");
                USERNAME = properties.getProperty("jdbc.username");
                PASSWORD = properties.getProperty("jdbc.password");
                DRIVER = properties.getProperty("jdbc.driver");
                
                // 加载驱动
                Class.forName(DRIVER);
            } else {
                System.err.println("无法找到db.properties配置文件");
                // 使用默认配置作为备选
                URL = "jdbc:mysql://localhost:3306/bookstore?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false";
                USERNAME = "root";
                PASSWORD = "root";
                DRIVER = "com.mysql.cj.jdbc.Driver";
                Class.forName(DRIVER);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}